from PySide2 import QtWidgets
from PySide2.QtGui import QIcon

from robotController import share
from robotController.binding import mapping_detail_bind
from PySide2.QtWidgets import QHeaderView, QTableWidgetItem, QPushButton, QHBoxLayout, QWidget, QMessageBox, \
    QAbstractItemView, QTableView, QApplication
import json
import requests

from robotController.elementUI.freezeTableWidget import masking_element
from robotController.util.TableWidgetUtil import TableWidgetUtil
from robotController.util.requestUtil import requestUtil


class bind:
    def __init__(self):

        self.ui = share.SI.main.ui
        self.mui = share.SI.mapping.ui

    def incident(self):

        # 映射源数据单元格平铺表格
        self.mui.original_mapping_tableWidget.setHorizontalHeaderLabels(['编号', '数据源', '版本'])
        self.mui.original_mapping_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.mui.original_mapping_tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)
        self.mui.original_mapping_tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.mui.original_mapping_tableWidget.horizontalHeader().setStyleSheet(
            "QHeaderView::section {background-color:#06193D;color: #ffffff;padding-left: 4px;border: 1px solid #6c6c6c;}")

        # 映射模板单元格平铺表格
        self.mui.template_mapping_tableWidget.setHorizontalHeaderLabels(['编号', '模板数据'])
        self.mui.template_mapping_tableWidget.setSelectionBehavior(QAbstractItemView.SelectRows)
        self.mui.template_mapping_tableWidget.setSelectionMode(QAbstractItemView.SingleSelection)
        self.mui.template_mapping_tableWidget.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        self.mui.template_mapping_tableWidget.horizontalHeader().setStyleSheet(
            "QHeaderView::section {background-color:#06193D;color: #ffffff;padding-left: 4px;border: 1px solid #6c6c6c;}")

        self.mui.template_mapping_tableWidget.itemClicked.connect(self.get_T_row)

        # 创建映射关系
        self.ui.create_mapping_button.clicked.connect(lambda: self.create_mapping())
        self.ui.create_mapping_button.setIcon(QIcon("./static/img/新建.png"))
        # 查询映射
        self.ui.mapping_select_button.clicked.connect(lambda: self.findMapping())
        self.ui.mapping_select_button.setIcon(QIcon("./static/img/查询.png"))
        # 映射确认
        self.mui.mapping_affirm_button.clicked.connect(lambda: self.mapping_affirm_fun())

    def get_T_row(self):
        name = self.mui.template_mapping_tableWidget.selectedItems()[0].text()
        # 创建名称，如果有.xls则去.xls,有空格去空格，有括号去括号
        if '.' in name:
            name = name.split('.')[0]

        name = name.replace(' ', '').replace('(', '').replace(')', '').replace('（', '').replace('）', '')
        # 将名称填至表名框
        self.mui.table_name.setPlainText(name)

    def create_mapping(self):

        # 获取查询条件
        origin_name = self.mui.origin_select_lineEdit.text() if self.mui.origin_select_lineEdit.text() != "" else "None"
        # 查询分组及单位
        from robotController.binding.home_bind import home_bind
        ug = home_bind().get_ug_comboBox_fun()
        template_name = self.mui.template_select_lineEdit.text() if self.mui.template_select_lineEdit.text() != "" else "None"

        # 获取源数据头列表
        original_dataList = requestUtil("/original/" + origin_name,"GET").dataMap['data']
        # 获取模板头列表
        template_dataList = requestUtil("/template/findByGroup/" + ug["group_value"] + "/" + ug["unit_value"] + "/" + template_name,"GET").dataMap['data']

        # 渲染数据
        TableWidgetUtil().render(self.mui.original_mapping_tableWidget,original_dataList,[{"key":"id","value":"id"},{"key":"编码","value":"code"},{"key":"名称","value":"name"},{"key":"版本","value":"version"}])
        TableWidgetUtil().render(self.mui.template_mapping_tableWidget,template_dataList,[{"key":"id","value":"id"},{"key":"名称","value":"name"}])
        TableWidgetUtil().head_color_show(self.mui.original_mapping_tableWidget,q=False)
        TableWidgetUtil().head_color_show(self.mui.template_mapping_tableWidget,q=False)
        self.mui.original_mapping_tableWidget.hideColumn(0)
        self.mui.template_mapping_tableWidget.hideColumn(0)
        share.jq.mapping_check_flag = 1
        self.mui.show()

    # 确认映射
    def mapping_affirm_fun(self):
        self.mui.original_mapping_tableWidget.showColumn(0)
        self.mui.template_mapping_tableWidget.showColumn(0)
        templateRow = self.mui.template_mapping_tableWidget.selectedItems()[0].text()
        originalRow = self.mui.original_mapping_tableWidget.selectedItems()[0].text()
        self.mui.original_mapping_tableWidget.hideColumn(0)
        self.mui.template_mapping_tableWidget.hideColumn(0)
        table_name = self.mui.table_name.toPlainText()

        if share.jq.mapping_check_flag == 1:
            url = share.RURL.backendUrl + "/mapping/create/" + originalRow + "/" + templateRow + "/" + table_name
        else:
            url = share.RURL.backendUrl + "/mapping/create1/" + originalRow + "/" + templateRow + "/" + table_name

        requests.encoding = 'utf-8'
        result = requests.request(method="GET", url=url, headers=share.token.headers)
        dataMap = json.loads(result.text)
        try:
            if dataMap["flag"] == True:
                QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", dataMap["message"])
                # 查询头元数据列表
                self.findMapping()
        except:
            QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", "新增映射失败")

    # 查询映射组信息
    def findMapping(self):
        # 查询分组及单位
        from robotController.binding.home_bind import home_bind
        ug = home_bind().get_ug_comboBox_fun()
        name = self.ui.mapping_select_lineEdit.text() if self.ui.mapping_select_lineEdit.text() != "" else "None"
        dataMap = requestUtil("/mapping/findByGroup/" + ug["group_value"] + "/" + ug["unit_value"] + "/" + name, "GET").dataMap

        for index, item in enumerate(dataMap["data"]):
            item["buttons"] = self.buttonForRow(item["id"], item["oname"], item["tname"])
        dataList = dataMap['data']
        # 准备表头数据
        head_list = [{'key': "久其表", "value": "tableName"}, {'key': "源数据", "value": "oname"},
                     {'key': "源数据版本", "value": "version"}, {'key': "模板数据", "value": "tname"},{'key': "分组", "value": "gname"},{'key': "单位", "value": "uname"},
                     {'key': "操作", "value": "buttons"}]
        TableWidgetUtil().render(self.ui.mapping_tableWidget, dataList, head_list)
        TableWidgetUtil().head_color_show(self.ui.mapping_tableWidget)

    # flag = True 开启编辑组
    def alter_template(self, id, name, tableName,flag):

        masking = masking_element()
        masking.mpShadeWindow.show()
        QApplication.processEvents()

        if flag == True:
            self.ui.fx_widget.show()
            # 公式框内容清空
            self.ui.formula_compile.clear()
        else:
            self.ui.fx_widget.hide()

        # 设置公式编辑表头
        self.ui.fx_lable.setText(tableName)
        if "科目余额" in name:
            # 科目余额表赋值
            mapping_detail_bind.data_bind(id).BData_KM()
            self.ui.mapping_original_border_widget.findChild(QTableView, "mapping_original_tableView").show()
            self.ui.mapping_original_border_widget.findChild(QTableView, "mapping_original_XJ_tableView").hide()
        else:
            mapping_detail_bind.data_bind(id).BData_XJ()
            self.ui.mapping_original_border_widget.findChild(QTableView, "mapping_original_tableView").hide()
            self.ui.mapping_original_border_widget.findChild(QTableView, "mapping_original_XJ_tableView").show()
        # 跳转至公式编辑页
        self.ui.stackedWidget.setCurrentIndex(5)
        masking.mpShadeWindow.hide()

    # 删除映射组
    def del_template(self, id):

        url = share.RURL.backendUrl + "/mapping/del/" + str(id)
        requests.encoding = 'utf-8'
        result = requests.request(method="GET", url=url, headers=share.token.headers)
        dataMap = json.loads(result.text)

        try:
            if dataMap["flag"] == True:
                QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", dataMap["message"])
                # 查询头元数据列表
                self.findMapping()
        except:
            QtWidgets.QMessageBox.about(self.ui.original_tableWidget, "信息提示框", "删除失败")

    # 列表内添加按钮
    def buttonForRow(self, id, name, tname):
        widget = QWidget()

        # 查看
        checkBtn = QPushButton('查看')
        checkBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:40px;
                                    border-style: outset;
                                    color:#192D9E;
                                    }
                                     
                                    QPushButton:hover{
                                    	color: #192D9E;
                                    	text-decoration:underline;
                                    }''')


        # 修改
        alterBtn = QPushButton('修改')
        alterBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:40px;
                                    border-style: outset;
                                    color:#192D9E;
                                    }
                                     
                                    QPushButton:hover{
                                    	color: #192D9E;
                                    	text-decoration:underline;
                                    }''')

        # 删除
        deleteBtn = QPushButton('删除')
        deleteBtn.setStyleSheet(''' QPushButton{
                                    text-align : center;
                                    background-color : transparent;
                                    height : 30px;
                                    width:40px;
                                    border-style: outset;
                                    color:red;}
                                     
                                    QPushButton:hover{
                                    	color: red;
                                    	text-decoration:underline;
                                    }''')

        checkBtn.clicked.connect(lambda: self.alter_template(id, name, tname,False))
        alterBtn.clicked.connect(lambda: self.alter_template(id, name, tname,True))
        deleteBtn.clicked.connect(lambda: self.del_template(id))

        hLayout = QHBoxLayout()
        hLayout.addWidget(checkBtn)
        hLayout.addWidget(alterBtn)
        hLayout.addWidget(deleteBtn)
        hLayout.setContentsMargins(5, 2, 5, 2)
        widget.setLayout(hLayout)
        return widget
